<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI文本生成器 - 后端服务版</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Segoe UI', 'Microsoft YaHei', sans-serif;
        }
        
        body {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: #333;
            min-height: 100vh;
            padding: 20px;
            display: flex;
            justify-content: center;
            align-items: center;
        }
        
        .container {
            width: 90%;
            max-width: 800px;
            background: rgba(255, 255, 255, 0.95);
            border-radius: 20px;
            box-shadow: 0 15px 30px rgba(0, 0, 0, 0.2);
            overflow: hidden;
            padding: 30px;
        }
        
        header {
            text-align: center;
            margin-bottom: 30px;
            padding-bottom: 20px;
            border-bottom: 1px solid #eee;
        }
        
        h1 {
            color: #2c3e50;
            font-size: 2.5rem;
            margin-bottom: 10px;
            background: linear-gradient(90deg, #667eea, #764ba2);
            -webkit-background-clip: text;
            background-clip: text;
            color: transparent;
        }
        
        .subtitle {
            color: #7f8c8d;
            font-size: 1.1rem;
        }
        
        .server-status {
            background: #e8f5e8;
            padding: 15px;
            border-radius: 10px;
            margin-bottom: 20px;
            border-left: 4px solid #4caf50;
            font-size: 0.9rem;
        }
        
        .server-status.error {
            background: #ffebee;
            border-left-color: #f44336;
        }
        
        .server-status.warning {
            background: #fff3e0;
            border-left-color: #ff9800;
        }
        
        .input-group {
            margin-bottom: 20px;
        }
        
        label {
            display: block;
            margin-bottom: 8px;
            font-weight: 600;
            color: #2c3e50;
        }
        
        input, textarea, select {
            width: 100%;
            padding: 12px 15px;
            border: 2px solid #e0e0e0;
            border-radius: 10px;
            font-size: 1rem;
            transition: all 0.3s;
        }
        
        input:focus, textarea:focus, select:focus {
            border-color: #667eea;
            outline: none;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }
        
        textarea {
            min-height: 120px;
            resize: vertical;
            line-height: 1.6;
        }
        
        .form-row {
            display: flex;
            gap: 20px;
            margin-bottom: 25px;
        }
        
        .form-row .input-group {
            flex: 1;
            margin-bottom: 0;
        }
        
        button {
            background: linear-gradient(90deg, #667eea, #764ba2);
            color: white;
            border: none;
            padding: 15px 30px;
            border-radius: 10px;
            font-size: 1.1rem;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s;
            width: 100%;
            margin-top: 10px;
        }
        
        button:hover:not(:disabled) {
            transform: translateY(-3px);
            box-shadow: 0 7px 15px rgba(102, 126, 234, 0.4);
        }
        
        button:disabled {
            opacity: 0.6;
            cursor: not-allowed;
            transform: none !important;
        }
        
        .secondary-btn {
            background: linear-gradient(90deg, #6c757d, #495057);
        }
        
        .secondary-btn:hover:not(:disabled) {
            box-shadow: 0 7px 15px rgba(108, 117, 125, 0.4);
        }
        
        .loading {
            display: none;
            text-align: center;
            margin: 20px 0;
            padding: 20px;
        }
        
        .spinner {
            border: 5px solid #f3f3f3;
            border-top: 5px solid #667eea;
            border-radius: 50%;
            width: 50px;
            height: 50px;
            animation: spin 1s linear infinite;
            margin: 0 auto 15px;
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        
        .preview-section {
            margin-top: 30px;
            padding: 20px;
            background: #f8f9fa;
            border-radius: 10px;
            display: none;
        }
        
        .preview-section h3 {
            margin-bottom: 15px;
            color: #2c3e50;
            display: flex;
            justify-content: between;
            align-items: center;
        }
        
        .preview-content {
            max-height: 400px;
            overflow-y: auto;
            padding: 20px;
            background: white;
            border-radius: 8px;
            border: 1px solid #e0e0e0;
            white-space: pre-wrap;
            line-height: 1.6;
            font-size: 1rem;
        }
        
        .api-info {
            font-size: 0.9rem;
            color: #666;
            margin: 10px 0;
            padding: 10px;
            background: #e9ecef;
            border-radius: 5px;
        }
        
        .word-count {
            display: flex;
            justify-content: space-between;
            margin-top: 5px;
            font-size: 0.9rem;
            color: #666;
        }
        
        .notification {
            position: fixed;
            top: 20px;
            right: 20px;
            padding: 15px 25px;
            background: #2ecc71;
            color: white;
            border-radius: 10px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
            transform: translateX(150%);
            transition: transform 0.4s;
            z-index: 1000;
        }
        
        .notification.error {
            background: #e74c3c;
        }
        
        .notification.warning {
            background: #f39c12;
        }
        
        .notification.show {
            transform: translateX(0);
        }
        
        .btn-group {
            display: flex;
            gap: 10px;
            margin-top: 15px;
        }
        
        .btn-group button {
            margin-top: 0;
        }
        
        .usage-stats {
            display: flex;
            justify-content: space-around;
            margin-top: 15px;
            padding: 10px;
            background: #e8f5e8;
            border-radius: 8px;
            font-size: 0.9rem;
        }
        
        .stat-item {
            text-align: center;
        }
        
        .stat-value {
            font-weight: bold;
            color: #667eea;
        }
        
        footer {
            text-align: center;
            margin-top: 30px;
            color: #7f8c8d;
            font-size: 0.9rem;
            padding-top: 20px;
            border-top: 1px solid #eee;
        }
    </style>
</head>
<body>
    <div class="container">
        <header>
            <h1>AI文本生成器</h1>
            <p class="subtitle">基于DeepSeek API的智能文本生成工具</p>
        </header>
        
        <div class="server-status" id="serverStatus">
            <div class="status-content">
                <span id="statusIcon">🔄</span>
                <span id="statusText">检查服务器连接状态...</span>
            </div>
        </div>
        
        <div class="input-group">
            <label for="prompt">📝 文本提示词</label>
            <textarea 
                id="prompt" 
                placeholder="请详细描述您想要生成的文本内容，例如：写一篇关于人工智能在教育领域应用的文章，包括个性化学习、智能辅导和教学评估等方面的内容..."
            >请写一篇关于人工智能对未来教育影响的文章，讨论个性化学习、智能教学系统和教育评估的创新，字数约500字。</textarea>
            <div class="word-count">
                <span>提示词长度: <span id="promptLength">0</span> 字</span>
                <span>推荐: 50-500字</span>
            </div>
        </div>
        
        <div class="form-row">
            <div class="input-group">
                <label for="wordCount">📊 文本长度</label>
                <select id="wordCount">
                    <option value="200">短文本 (200字)</option>
                    <option value="300">简短文本 (300字)</option>
                    <option value="500" selected>中等文本 (500字)</option>
                    <option value="800">长文本 (800字)</option>
                    <option value="1000">超长文本 (1000字)</option>
                </select>
            </div>
            
            <div class="input-group">
                <label for="writingStyle">🎨 写作风格</label>
                <select id="writingStyle">
                    <option value="professional">专业风格</option>
                    <option value="academic">学术风格</option>
                    <option value="casual">随意风格</option>
                    <option value="creative">创意风格</option>
                    <option value="news">新闻风格</option>
                </select>
            </div>
        </div>
        
        <div class="input-group">
            <label for="fileName">💾 文件名称</label>
            <input 
                type="text" 
                id="fileName" 
                value="AI教育应用文章" 
                placeholder="输入保存的文件名（不含扩展名）"
            >
        </div>
        
        <div class="loading" id="loading">
            <div class="spinner"></div>
            <p id="loadingText">正在连接AI服务，请稍候...</p>
            <div class="usage-stats" id="usageStats" style="display: none;">
                <div class="stat-item">
                    <div class="stat-label">API服务</div>
                    <div class="stat-value" id="statApi">-</div>
                </div>
                <div class="stat-item">
                    <div class="stat-label">生成进度</div>
                    <div class="stat-value" id="statProgress">-</div>
                </div>
                <div class="stat-item">
                    <div class="stat-label">预计耗时</div>
                    <div class="stat-value" id="statTime">-</div>
                </div>
            </div>
        </div>
        
        <button id="generateBtn">🚀 生成文本内容</button>
        
        <div class="preview-section" id="previewSection">
            <h3>
                <span>📄 生成的文本内容</span>
                <span style="font-size: 0.9rem; color: #666; font-weight: normal;">字数: <span id="contentLength">0</span> 字</span>
            </h3>
            
            <div class="api-info" id="apiInfo">
                <strong>服务信息:</strong> 正在获取...
            </div>
            
            <div class="preview-content" id="previewContent">
                内容加载中...
            </div>
            
            <div class="btn-group">
                <button id="saveBtn" class="secondary-btn">💾 下载文本文件</button>
                <button id="copyBtn" class="secondary-btn">📋 复制到剪贴板</button>
                <button id="newGenerateBtn">🔄 重新生成</button>
            </div>
        </div>
        
        <footer>
            <p>AI文本生成器 &copy; 2025 | 基于DeepSeek API | 人工智能通识课程实验</p>
            <p style="font-size: 0.8rem; margin-top: 5px;">服务器: <span id="serverUrl">http://localhost:3000</span></p>
        </footer>
    </div>
    
    <div class="notification" id="notification">操作成功！</div>

    <script>
        class AITextGenerator {
            constructor() {
                this.API_BASE = 'http://localhost:3000/api';
                this.init();
            }
            
            init() {
                this.bindEvents();
                this.checkServerStatus();
                this.updatePromptLength();
            }
            
            bindEvents() {
                // 生成按钮
                document.getElementById('generateBtn').addEventListener('click', () => this.generateText());
                
                // 保存按钮
                document.getElementById('saveBtn').addEventListener('click', () => this.saveFile());
                
                // 复制按钮
                document.getElementById('copyBtn').addEventListener('click', () => this.copyToClipboard());
                
                // 重新生成按钮
                document.getElementById('newGenerateBtn').addEventListener('click', () => this.newGenerate());
                
                // 提示词长度监控
                document.getElementById('prompt').addEventListener('input', () => this.updatePromptLength());
                
                // 文件名输入提示
                document.getElementById('fileName').addEventListener('focus', function() {
                    if (this.value === 'AI教育应用文章') {
                        this.select();
                    }
                });
            }
            
            async checkServerStatus() {
                const statusElement = document.getElementById('serverStatus');
                const statusIcon = document.getElementById('statusIcon');
                const statusText = document.getElementById('statusText');
                
                try {
                    const response = await fetch(`${this.API_BASE}/generate/status`);
                    const data = await response.json();
                    
                    statusIcon.textContent = '✅';
                    statusText.textContent = `服务器连接正常 - 可用API服务: ${data.availableAPIs.join(', ') || '无'} (共${data.total}个)`;
                    statusElement.className = 'server-status';
                    
                } catch (error) {
                    statusIcon.textContent = '❌';
                    statusText.textContent = '服务器连接失败 - 请确保后端服务正在运行 (npm start)';
                    statusElement.className = 'server-status error';
                }
            }
            
            updatePromptLength() {
                const prompt = document.getElementById('prompt').value;
                document.getElementById('promptLength').textContent = prompt.length;
            }
            
            async generateText() {
                const prompt = document.getElementById('prompt').value.trim();
                const wordCount = document.getElementById('wordCount').value;
                const writingStyle = document.getElementById('writingStyle').value;
                
                // 验证输入
                if (!prompt) {
                    this.showNotification('请输入文本提示词', 'error');
                    document.getElementById('prompt').focus();
                    return;
                }
                
                if (prompt.length < 5) {
                    this.showNotification('提示词太短，请提供更详细的描述', 'warning');
                    return;
                }
                
                this.showLoading(true);
                
                try {
                    const response = await fetch(`${this.API_BASE}/generate`, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                        },
                        body: JSON.stringify({
                            prompt,
                            wordCount: parseInt(wordCount),
                            writingStyle
                        })
                    });
                    
                    const data = await response.json();
                    
                    if (!response.ok) {
                        throw new Error(data.error || '服务器返回错误');
                    }
                    
                    if (data.success) {
                        this.displayGeneratedText(data);
                        this.showNotification('文本生成成功！', 'success');
                    } else {
                        throw new Error(data.error || '生成失败');
                    }
                    
                } catch (error) {
                    console.error('生成失败:', error);
                    this.showNotification(`生成失败: ${error.message}`, 'error');
                } finally {
                    this.showLoading(false);
                }
            }
            
            displayGeneratedText(data) {
                const content = data.content;
                const apiUsed = data.apiUsed || '未知';
                const timestamp = data.timestamp ? new Date(data.timestamp).toLocaleString() : new Date().toLocaleString();
                
                document.getElementById('previewContent').textContent = content;
                document.getElementById('contentLength').textContent = content.length;
                document.getElementById('apiInfo').innerHTML = `
                    <strong>服务信息:</strong> ${apiUsed} | 
                    <strong>生成时间:</strong> ${timestamp}
                    ${data.usage ? ` | <strong>Token使用:</strong> ${data.usage.total_tokens || 'N/A'}` : ''}
                `;
                
                document.getElementById('previewSection').style.display = 'block';
                
                // 滚动到预览区域
                setTimeout(() => {
                    document.getElementById('previewSection').scrollIntoView({ 
                        behavior: 'smooth',
                        block: 'start'
                    });
                }, 100);
            }
            
            saveFile() {
                const fileName = document.getElementById('fileName').value.trim() || '生成的文本';
                const content = document.getElementById('previewContent').textContent;
                
                if (!content || content === '内容加载中...') {
                    this.showNotification('没有可保存的内容', 'warning');
                    return;
                }
                
                const blob = new Blob([content], { type: 'text/plain;charset=utf-8' });
                const url = URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.href = url;
                a.download = `${fileName}.txt`;
                document.body.appendChild(a);
                a.click();
                document.body.removeChild(a);
                URL.revokeObjectURL(url);
                
                this.showNotification(`文件 ${fileName}.txt 下载成功！`);
            }
            
            async copyToClipboard() {
                const content = document.getElementById('previewContent').textContent;
                
                if (!content || content === '内容加载中...') {
                    this.showNotification('没有可复制的内容', 'warning');
                    return;
                }
                
                try {
                    await navigator.clipboard.writeText(content);
                    this.showNotification('内容已复制到剪贴板！');
                } catch (error) {
                    // 降级方案
                    const textArea = document.createElement('textarea');
                    textArea.value = content;
                    document.body.appendChild(textArea);
                    textArea.select();
                    document.execCommand('copy');
                    document.body.removeChild(textArea);
                    this.showNotification('内容已复制到剪贴板！');
                }
            }
            
            newGenerate() {
                // 清空当前内容，但保留设置
                document.getElementById('previewContent').textContent = '内容加载中...';
                document.getElementById('previewSection').style.display = 'none';
                
                // 滚动到顶部
                window.scrollTo({ top: 0, behavior: 'smooth' });
            }
            
            showLoading(show) {
                const loading = document.getElementById('loading');
                const generateBtn = document.getElementById('generateBtn');
                const loadingText = document.getElementById('loadingText');
                const usageStats = document.getElementById('usageStats');
                
                if (show) {
                    loading.style.display = 'block';
                    generateBtn.disabled = true;
                    generateBtn.textContent = '生成中...';
                    usageStats.style.display = 'flex';
                    
                    // 模拟进度更新
                    this.updateLoadingProgress();
                } else {
                    loading.style.display = 'none';
                    generateBtn.disabled = false;
                    generateBtn.textContent = '🚀 生成文本内容';
                    usageStats.style.display = 'none';
                    clearInterval(this.progressInterval);
                }
            }
            
            updateLoadingProgress() {
                const steps = [
                    '连接AI服务...',
                    '分析提示词...',
                    '生成内容...',
                    '优化输出...',
                    '即将完成...'
                ];
                let currentStep = 0;
                
                document.getElementById('statApi').textContent = 'DeepSeek';
                document.getElementById('statProgress').textContent = '0%';
                document.getElementById('statTime').textContent = '10-30秒';
                
                this.progressInterval = setInterval(() => {
                    const progress = Math.min(20 + (currentStep * 20), 95);
                    document.getElementById('statProgress').textContent = `${progress}%`;
                    document.getElementById('loadingText').textContent = steps[currentStep];
                    
                    currentStep = (currentStep + 1) % steps.length;
                }, 2000);
            }
            
            showNotification(message, type = 'success') {
                const notification = document.getElementById('notification');
                notification.textContent = message;
                notification.className = `notification ${type} show`;
                
                setTimeout(() => {
                    notification.classList.remove('show');
                }, 4000);
            }
        }
        
        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', () => {
            new AITextGenerator();
        });
        
        // 显示当前服务器URL
        document.getElementById('serverUrl').textContent = window.location.origin.replace('5500', '3000');
    </script>
</body>
</html>